package org.hepeng.app;

import org.hepeng.fabric.gateway.pool.GatewayKey;
import org.hepeng.fabric.gateway.pool.GatewayKeyProvider;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

/**
 * @author he peng
 * @date 2022/3/25
 */

public class JdbcGatewayKeyProvider implements GatewayKeyProvider {


    final JdbcTemplate jdbc;

    public JdbcGatewayKeyProvider(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }

    @Override
    public GatewayKey getKey(Object obj) {

        if (obj instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) obj;
            String key = request.getParameter("id");
            Map<String, Object> map = jdbc.queryForMap("select * from identity where id = '" + key + "' ");
            if (Objects.nonNull(map)) {
                return new GatewayKey()
                        .setId((String) map.get("id"))
                        .setMspId((String) map.get("msp_id"))
                        .setX509CertificatePem((String) map.get("sign_cert_pem"))
                        .setPrivateKeyPem((String) map.get("priv_key_pem"))
                        .setChannel((String) map.get("channel"));
            }
        }



        return null;
    }
}
